package logic.nodes.damagable.shield;

import java.util.ArrayList;
import java.util.List;

import settings.GraphicSettings;
import logic.nodes.damagable.DamagableNode;

import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.state.BlendState;
import com.jme.system.DisplaySystem;

import fileHandling.language.options.OptionValues;

public class Shields extends Node {
	
	private static final long serialVersionUID = 1L;
		
	private DamagableNode node;
	private float maxDist, impactDist;
	private boolean useShader;
	private List<ShieldEffectObject> lastImpacts, removeImpacts;
	
	public Shields(DamagableNode node) {
		super("Shield of " + node.getName());
		this.node = node;
		
		lastImpacts = new ArrayList<ShieldEffectObject>();
		removeImpacts = new ArrayList<ShieldEffectObject>();
		
		maxDist = node.getShieldBound().getRadius() / 2f;
		
		impactDist = maxDist;
		
		setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
		
		BlendState bs = DisplaySystem.getDisplaySystem().getRenderer().createBlendState();
		bs.setBlendEnabled(true);
		bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
		bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
		bs.setTestEnabled(true);
		bs.setTestFunction(BlendState.TestFunction.GreaterThan);
		setRenderState(bs);
		
		updateQuality();
	}
	
	public void collision(Vector3f location) {
		if(node.isDestroyed() || node.getCurrentShield() == 0) return;
		
		clearNearImpacts(location);
		
		ShieldEffectObject object = null;
		if(useShader) object = new ShieldSphere(node, this, location, maxDist);
		else object = new ShieldQuad(node, this, location, maxDist);
		
		lastImpacts.add(object);
		attachChild(object);
		
		node.attachChild(this);
	}
	
	private void clearNearImpacts(Vector3f loc) {
		for(ShieldEffectObject obj : lastImpacts) {
			if(obj.getLocation().distance(loc) < impactDist) {
				removeImpacts.add(obj);
			}
		}
		for(ShieldEffectObject obj : removeImpacts) {
			obj.disable();
		}
		removeImpacts.clear();
	}
	
	public void removeImpact(ShieldEffectObject loc) {
		lastImpacts.remove(loc);
	}
	
	public void updateQuality() {
		useShader = !GraphicSettings.get().getShaderQualityString().equals(OptionValues.Low.toString());
	}
}